package org.seaurchin.index;

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.IndexWriter;

import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;

/** Index all text files defined in the doclist file, modified from the 
 *  initial Lucene demo class. 
 *  The doclist file contains a list of files to be indexed.  Each line 
 *  corresponds to a single file entry, with additional fields for url and category
 *  defined as:  absolute_file_path, url, category
*/
public class IndexFiles {
  
  private IndexFiles() {}

  static final File INDEX_DIR = new File("index");
  
  /** Index all text files under a directory. */
  public static void main(String[] args) {
    if (args.length == 0) {
      String usage = "java org.apache.seaurchin.index.IndexFiles doclist_file";
      System.err.println("Usage: " + usage);
      System.exit(1);
    }

    if (INDEX_DIR.exists()) {
      System.out.println("Cannot save index to '" +INDEX_DIR+ "' directory, please delete it first");
      System.exit(1);
    }
    
    List<String[]> filelist = new ArrayList<String[]>();
    // Open the doclist file save content into ArrayList
    try {
    	BufferedReader in = new BufferedReader(new FileReader(args[0]));
	String line = null;
	while ((line = in.readLine()) != null) {
	    String[] entry = line.split(",");
	    System.out.println("Entry read: " + entry[0] + ", "
			+ entry[1] +", " + entry[2]);
	    filelist.add(entry);
	}
    }
    catch(IOException e) {
	System.err.println("IOException caught: " + e.getMessage());
    }

    Date start = new Date();
    try {
      IndexWriter writer = new IndexWriter(INDEX_DIR, new StandardAnalyzer(), true);
      System.out.println("Indexing to directory '" +INDEX_DIR+ "'...");
      indexDocs(writer, filelist);
      System.out.println("Optimizing...");
      writer.optimize();
      writer.close();

      Date end = new Date();
      System.out.println(end.getTime() - start.getTime() + " total milliseconds");

    } catch (IOException e) {
      System.out.println(" caught a " + e.getClass() +
       "\n with message: " + e.getMessage());
    }
  }

  static void indexDocs(IndexWriter writer, List<String[]> doclist)
    throws IOException {
    
    // going through each file entry in the list and perform index function
    int size = doclist.size();
    for (int i=0; i<size; i++) {
     	String[] fileEntry = doclist.get(i);
	if(fileEntry.length < 3)
	  throw new IOException("Invalid file entry for " + fileEntry[0]);

	File file = new File(fileEntry[0]);	
        System.out.println("adding " + fileEntry[0] + ", " + fileEntry[1] + ", " + fileEntry[2]);
        try {
          writer.addDocument(FileDocument.Document(file, fileEntry[1], fileEntry[2]));
        }
        // at least on windows, some temporary files raise this exception with an "access denied" message
        // checking if the file can be read doesn't help
        catch (FileNotFoundException fnfe) {
          ;
        }
      }
  }
  
}
